package com.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.constant.MqttMessageType;
import com.dao.PlacedHospitalMapper;
import com.dao.PlacedHospitalRelationSysUserMapper;
import com.dao.SysUserMapper;
import com.dao.VenderDeviceMapper;
import com.emqx.MqttMessageDTO;
import com.emqx.MqttMessageSender;
import com.exception.BusinessException;
import com.github.pagehelper.ISelect;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.model.PlacedHospital;
import com.model.PlacedHospitalRelationSysUser;
import com.model.SysUser;
import com.page.GenericPage;
import com.po.*;
import com.result.Result;
import com.service.PlacedHospitalService;
import com.utils.CurrentLoginUserAgent;
import com.utils.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: chihaojie
 * @Date: 2019/5/29 16:13
 * @Version 1.0
 * @Note
 */
@Slf4j
@Service
public class PlacedHospitalServiceImpl implements PlacedHospitalService {


    @Autowired
    private PlacedHospitalMapper placedHospitalMapper;

    @Autowired
    private VenderDeviceMapper venderDeviceMapper;

    @Autowired
    private PlacedHospitalRelationSysUserMapper placedHospitalRelationSysUserMapper;

    @Autowired
    private SysUserMapper sysUserMapper;


    @Autowired
    private MqttMessageSender mqttMessageSender;

    @Override
    @Transactional
    public Result<PlacedHospital> save(PlacedHospitalPO hospitalPO) {
        PlacedHospital placedHospital = new PlacedHospital();
        BeanUtils.copyProperties(hospitalPO, placedHospital);
        Date time = new Date();
        placedHospital.setCreateTime(time);
        placedHospital.setUpdateTime(time);
        placedHospital.setUpdated(placedHospital.getCreated());
        placedHospital.setStatus((byte) 2);  //状态：0删除 1已发布 2未发布
        placedHospital.setTopic(String.valueOf(System.currentTimeMillis()));
        placedHospitalMapper.insertSelective(placedHospital);

        placedHospital.setHospitalNum(org.apache.commons.lang.StringUtils.leftPad(String.valueOf(placedHospital.getId()), 6, "0"));
        placedHospitalMapper.updateByPrimaryKeySelective(placedHospital);
        return new Result<PlacedHospital>().ok(placedHospital);
    }


    @Override
    @Transactional
    public Result<Boolean> modifyById(PlacedHospitalModifyPO placedHospitalModifyPO) {
        PlacedHospital placedHospital = new PlacedHospital();
        BeanUtils.copyProperties(placedHospitalModifyPO, placedHospital);

        if (ObjectUtils.isEmpty(placedHospital.getId())){
            throw new BusinessException("参数异常");
        }

        PlacedHospital hospital = placedHospitalMapper.selectByPrimaryKey(placedHospitalModifyPO.getId());

        if (ObjectUtils.isEmpty(hospital)){
            throw new BusinessException("参数异常");
        }

//        if (!ObjectUtils.isEmpty(placedHospital.getSysUserId())) {
//            if (SessionUtil.getCurrentUserType() == 2 || SessionUtil.getCurrentUserType() == 3) {
//
//                PlacedHospitalRelationSysUser placedHospitalRelationSysUser = new PlacedHospitalRelationSysUser();
//
//                //先删除再绑定
////                placedHospitalRelationSysUser.setHospitalId(placedHospitalModifyPO.getId());
////                placedHospitalRelationSysUser.setSysUserId(SessionUtil.getCurrentUserId());
////                placedHospitalRelationSysUserMapper.deleteByCondition(placedHospitalRelationSysUser);
//
//                if (placedHospitalModifyPO.getSysUserId() != 0) {
//                    placedHospitalRelationSysUser.setSysUserId(placedHospitalModifyPO.getSysUserId());
//                    placedHospitalRelationSysUser.setUserType(3);
//                    placedHospitalRelationSysUser.setLeaderId(SessionUtil.getCurrentUserLeaderId());
//                    placedHospitalRelationSysUserMapper.insert(placedHospitalRelationSysUser);
//                }
//
//            } else if (SessionUtil.getCurrentUserType() == 1) {
//                PlacedHospitalRelationSysUser placedHospitalRelationSysUser = new PlacedHospitalRelationSysUser();
//                placedHospitalRelationSysUser.setHospitalId(placedHospitalModifyPO.getId());
//                placedHospitalRelationSysUserMapper.deleteByCondition(placedHospitalRelationSysUser);
//                if (ObjectUtils.isEmpty(placedHospital.getAdvertisementId())){
//                    placedHospital.setAdvertisementId(0L);
//                }
//                placedHospitalMapper.updateByPrimaryKeySelective(placedHospital);
//                venderDeviceMapper.updateAgentByHospitalId(placedHospital.getSysUserId()==0? null:placedHospital.getSysUserId(),placedHospital.getId());
//            }
//        } else {
            Date time = new Date();
            placedHospital.setUpdateTime(time);
            placedHospital.setUpdated(SessionUtil.getCurrentUser().getUsername());
            placedHospitalMapper.updateByPrimaryKeySelective(placedHospital);
//        }



        Date now = new Date();
        MqttMessageDTO message = new MqttMessageDTO();
        message.setMsgSender("server_in");
        message.setMsgReceiver(hospital.getTopic());
        message.setMsgType(MqttMessageType.FLUSH_HOSPITAL);
        message.setMsgBody("");
        message.setSendTime(now);
//                message.setMsgIdentifier(msgIdent);
        mqttMessageSender.send(message);


//        placedHospitalMapper.updateByPrimaryKeySelective(placedHospital);
        return new Result<>().ok();
    }

    @Override
    public Result<Boolean> removeById(Long id) {
        placedHospitalMapper.deleteByPrimaryKey(id);
        return new Result<>().ok();
    }



    @Override
    public Result<GenericPage<PlacedHospital>> queryByUserid(Integer pageNo, Integer pageSize, Long userId) {
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(userId);
        if (ObjectUtils.isEmpty(sysUser)){
            throw  new BusinessException("用户不存在");
        }
        PageHelper.startPage(pageNo, pageSize);
        List<PlacedHospital> placedHospitals = new ArrayList<>();
        PageInfo<PlacedHospital> pageInfo = PageHelper.startPage(pageNo, pageSize).doSelectPageInfo(() -> {
            if (sysUser.getUserType() ==1){
                placedHospitals.addAll(placedHospitalMapper.selectByCondition(new PlacedHospital()));
            }else if (sysUser.getUserType() ==2){
                PlacedHospital c = new PlacedHospital();
                c.setSysUserId(sysUser.getId());
                placedHospitals.addAll(placedHospitalMapper.selectByCondition(c));
            }else{
                placedHospitals.addAll(placedHospitalMapper.selectBySysUserId(userId));
            }
        });
        GenericPage<PlacedHospital> genericPage = new GenericPage<>(pageSize, pageInfo.getTotal(), placedHospitals);
        return new Result<GenericPage<PlacedHospital>>().ok(genericPage);
    }

    @Override
    public Result<Boolean> userAddHospital(Long userId,Long hospitalId){
        PlacedHospitalRelationSysUser placedHospitalRelationSysUser = new PlacedHospitalRelationSysUser();
        placedHospitalRelationSysUser.setHospitalId(hospitalId);
        placedHospitalRelationSysUser.setSysUserId(userId);
        List<PlacedHospitalRelationSysUser> placedHospitalRelationSysUsers = placedHospitalRelationSysUserMapper.selectByCondition(placedHospitalRelationSysUser);

        SysUser sysUser = sysUserMapper.selectByPrimaryKey(userId);
        if (sysUser.getUserType() == 2){
            //代理商，删除目标医院的代理商绑定关系
            PlacedHospitalRelationSysUser delete = new PlacedHospitalRelationSysUser();
            delete.setUserType(2);
            delete.setHospitalId(hospitalId);
            placedHospitalRelationSysUserMapper.deleteByCondition(delete);
        }

        placedHospitalRelationSysUser.setUserType(sysUser.getUserType());
        placedHospitalRelationSysUser.setLeaderId(sysUser.getLeaderId());
        if (!ObjectUtils.isEmpty(placedHospitalRelationSysUser)){
            placedHospitalRelationSysUserMapper.insert(placedHospitalRelationSysUser);
        }
        return new Result<>().ok();
    }

    @Override
    public Result<Boolean> userRemoveHospital(Long userId,Long hospitalId){
        PlacedHospitalRelationSysUser placedHospitalRelationSysUser = new PlacedHospitalRelationSysUser();
        placedHospitalRelationSysUser.setHospitalId(hospitalId);
        placedHospitalRelationSysUser.setSysUserId(userId);
        List<PlacedHospitalRelationSysUser> placedHospitalRelationSysUsers = placedHospitalRelationSysUserMapper.selectByCondition(placedHospitalRelationSysUser);
        if (!ObjectUtils.isEmpty(placedHospitalRelationSysUser)){
            placedHospitalRelationSysUserMapper.deleteByCondition(placedHospitalRelationSysUser);
        }
        return new Result<>().ok();
    }




    @Override
    public Result<GenericPage<PlacedHospital>> queryAll(PlacedHospitalSelectPO placedHospitalSelectPO) {
//        log.info(JSON.toJSONString(placedHospitalSelectPO));
//        System.out.println(JSON.toJSONString(placedHospitalSelectPO));
        int pageNo = placedHospitalSelectPO.getPageNo() == 0 ? 1 : placedHospitalSelectPO.getPageNo();
        int pageSize = placedHospitalSelectPO.getPageSize() == 0 ? 10 : placedHospitalSelectPO.getPageSize();
        PageHelper.startPage(pageNo, pageSize);

        PlacedHospital placedHospital = new PlacedHospital();

        BeanUtils.copyProperties(placedHospitalSelectPO, placedHospital);

//        placedHospital.setSysUserId(CurrentLoginUserAgent.getBusinessId());


        List<PlacedHospital> placedHospitals = new ArrayList<>();
        PageInfo<PlacedHospital> pageInfo = PageHelper.startPage(pageNo, pageSize).doSelectPageInfo(() -> {
//            if (SessionUtil.getCurrentUserType() == 3) {
//                //三级用户
//                placedHospitals.addAll(placedHospitalMapper.selectBySysUserIdType3(ObjectUtils.isEmpty(placedHospitalSelectPO.getSysUserId()) ? SessionUtil.getCurrentUserId() : placedHospitalSelectPO.getSysUserId()));
//            } else if (SessionUtil.getCurrentUserType() == 2) {
//                //二级用户 代理商
//                if (ObjectUtils.isEmpty(placedHospitalSelectPO.getSysUserId())) {
//                    // 获取代理商本身的医院
//                    placedHospital.setSysUserId(SessionUtil.getCurrentUserId());
//                    placedHospitals.addAll(placedHospitalMapper.selectByCondition(placedHospital));
//                } else {
//                    //获取指定账号名下的医院
//                    placedHospitals.addAll(placedHospitalMapper.selectBySysUserIdType3(placedHospitalSelectPO.getSysUserId()));
//                }
//            } else if (SessionUtil.getCurrentUserType() == 1) {
                // 以及用户  root
                if (ObjectUtils.isEmpty(placedHospitalSelectPO.getSysUserId())) {
                    // 获取所有医院
//                    placedHospital.setSysUserId(SessionUtil.getCurrentUserId());
                    placedHospitals.addAll(placedHospitalMapper.selectByCondition(placedHospital));
                } else {
                    //获取指定代理商账号名下的医院
                    placedHospital.setSysUserId(placedHospitalSelectPO.getSysUserId());
                    placedHospitals.addAll(placedHospitalMapper.selectByCondition(placedHospital));
                }
//            }
        });

        GenericPage<PlacedHospital> genericPage = new GenericPage<>(pageSize, pageInfo.getTotal(), placedHospitals);
        return new Result<GenericPage<PlacedHospital>>().ok(genericPage);
    }

    @Override
    public Result<PlacedHospital> queryById(Long id) {
        PlacedHospital placedHospital = placedHospitalMapper.selectByPrimaryKey(id);
        return new Result<PlacedHospital>().ok(placedHospital);
    }

    @Override
    public Result<Boolean> bindAdvertisement(AdvertisementBindPO advertisementBindPO) {

        if (StringUtils.isEmpty(advertisementBindPO.getAdvertisementId()) || StringUtils.isEmpty(advertisementBindPO.getHospitalIds())) {
            return new Result<>().error("传参数异常");
        }
        List<AdvertisementIdAndHospitalIdPO> list = new ArrayList<>();

        AdvertisementIdAndHospitalIdPO map = null;
        for (Long hId : advertisementBindPO.getHospitalIds()) {
            map = new AdvertisementIdAndHospitalIdPO();
            map.setHospitalId(hId);
            map.setAdvertisementId(advertisementBindPO.getAdvertisementId());
            list.add(map);
        }
        int update = placedHospitalMapper.bindAdvertsementIdsById(list);
        for (Long id : advertisementBindPO.getHospitalIds()){
            PlacedHospital hospital = placedHospitalMapper.selectByPrimaryKey(id);
            if (hospital!=null){
                Date now = new Date();
                MqttMessageDTO message = new MqttMessageDTO();
                message.setMsgSender("server_in");
                message.setMsgReceiver(hospital.getTopic());
                message.setMsgType(MqttMessageType.CHECK_ADVERTISEMENT_VERSION);
                message.setMsgBody("");
                message.setSendTime(now);
//                message.setMsgIdentifier(msgIdent);
                mqttMessageSender.send(message);
            }

        }

        return new Result<>().ok();
    }


    @Override
    public Result<Boolean> unbindAdvertisement(List<Long> hospitalIds) {

        int update = placedHospitalMapper.unbindAdvertisement(hospitalIds);

        for (Long id : hospitalIds){
            PlacedHospital hospital = placedHospitalMapper.selectByPrimaryKey(id);
            if (hospital!=null){
                Date now = new Date();
                MqttMessageDTO message = new MqttMessageDTO();
                message.setMsgSender("server_in");
                message.setMsgReceiver(hospital.getTopic());
                message.setMsgType(MqttMessageType.CHECK_ADVERTISEMENT_VERSION);
                message.setMsgBody("");
                message.setSendTime(now);
//                message.setMsgIdentifier(msgIdent);
                mqttMessageSender.send(message);
            }

        }
        return new Result<>().ok();
    }


    @Override
    public Result<Boolean> publishAdvertiseByHospitalId(Long hospitalId) {
        PlacedHospital hospital = placedHospitalMapper.selectByPrimaryKey(hospitalId);

//        for (PlacedHospital hospital:placedHospitals){
        if (!StringUtils.isEmpty(hospital.getTopic())) {
            //3.通知app端
            //发送通知

            JSONObject body = new JSONObject();
            body.put("advertisement_id", hospital.getAdvertisementId());

            Date now = new Date();
            MqttMessageDTO message = new MqttMessageDTO();
            message.setMsgSender("server_in");
            message.setMsgReceiver(hospital.getTopic());
            message.setMsgType(MqttMessageType.CHECK_ADVERTISEMENT_VERSION);
            message.setMsgBody(body.toJSONString());
            message.setSendTime(now);
//                message.setMsgIdentifier(msgIdent);
            mqttMessageSender.send(message);
        }
//        }

        return new Result<>().ok();


    }


}
